<template>
	<div class="cmt-container">
		<h4>发表评论</h4>
		<hr>
		<textarea placeholder="请输入要BB的内容(最多吐槽120字)" maxlength="120" v-model="msg">
		
		</textarea>
		<mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
		<div class="cmt-list">
			<div class="cmt-item" v-for="(item,index) in comment" :key="item.add_time">
				<div class="cmt-title">
					第{{index +1}}楼 &nbsp;&nbsp;用户:{{item.user_name}} &nbsp;&nbsp;发表时间:{{item.add_time | dataFormt}}
				</div>
				<div class="cmt-body">
					{{item.content}}
				</div>
			</div>
			<div class="cmt-item" v-if="nocoment">
				<div class="cmt-title">
					这里还没人评论哦
				</div>
				<div class="cmt-body">
					这里还没人评论哦
				</div>
			</div>
		</div>
		<mt-button type="danger" size="large" plain >加载更多</mt-button>
	</div>
</template>

<script>
	import {Toast} from 'mint-ui'
	export default{
		data(){
			return{
				id:this.$route.params.id,
				comment:[],//获取到的评论
				nocoment:false,//当该新闻没有评论的时候显示为true
				pageindex:1 ,//默认展示第一页数据
				add_time:new Date(),//评论时间
				msg:'' ,//这是评论输入的内容
				user_name:'小王',//写死的用户名
			}
		},
		created(){
			this.getComments()
		},
		methods:{
			getComments(){ //获取评论
				this.axios.get('/getcomment'+'?id='+this.id+'&pageindex='+this.pageindex)
				.then(result => {
					Toast('获取评论成功')
					console.log(result.data)
					var com=result.data.comment
					com == undefined ? this.nocoment=true : com
					if(result.data.err_code == 0){
						this.comment = com
					}else{
						Toast('获取评论失败')
					}
				})
			},
			postComment(){ //发表评论
				//console.log(this.add_time.toString())
				//校验评论内容
				if(this.msg.trim().length ===0){
					return Toast('评论内容不能为空!')
				}
				
				this.axios.post('/postcomment'+'?id='+this.id,{
					user_name:'小王',
					add_time:this.add_time.toString(),
					content:this.msg.trim()  //去空格
				})
				 .then(result => {
					 if(result.data.err_code == 0){
						Toast('评论成功')
						//1. 拼接评论对象到comment
						var cmt={user_name:this.user_name,add_time:this.add_time,content:this.msg.trim()}
						this.comment.unshift(cmt)
						this.msg=''
					 }else{
					 	Toast('发表评论失败')
					 }
					 
				 })
			}
		}
	}
</script>

<style lang="scss" scoped>
	.cmt-container{
		h4{
			font-size: 14px;
		}
		textarea{
			font-size: 14px;
			height:85px;
			margin: 0;
		}
		.cmt-list{
			margin: 10px 0;
			.cmt-item{
				font-size: 12px;
				.cmt-title{
					background: #ccc;
					line-height: 30px;
				}
				.cmt-body{
					line-height:30px;
					text-indent: 2em;
				}
			}
		}
	}
</style>
